/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.phonebooksharing.android.activities.main;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import com.phonebooksharing.android.activities.pref.PreferencesActivity;
import com.phonebooksharing.android.activities.setupwizard.SetupWizard1;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.HttpManager;
import com.phonebooksharing.android.util.IOUtilities;
import com.phonebooksharing.android.util.NetworkHandlerTask;

/**
 * Displays an EULA ("End User License Agreement") that the user has to accept before
 * using the application. Your application should call {@link EulaLicenseAgreement#showEula(android.app.Activity)}
 * in the onCreate() method of the first activity. If the user accepts the EULA, it will never
 * be shown again. If the user refuses, {@link android.app.Activity#finish()} is invoked
 * on your activity.
 */
public class EulaLicenseAgreement {
    /**
     * Displays the EULA if necessary. This method should be called from the onCreate()
     * method of your main Activity.
     *
     * @param activity The Activity to finish if the user rejects the EULA.
     */
    public static void showEula(final Activity activity, final boolean isRunSetup) {
        final SharedPreferences preferences = activity.getSharedPreferences(PreferencesActivity.PREFERENCE_FILE_NAME,
                Activity.MODE_PRIVATE);
        if (!preferences.getBoolean(PreferencesActivity.PREF_EULA_ACCEPTED, false) || !isRunSetup) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("License agreement");
            builder.setCancelable(true);
            builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    accept(preferences);
                    if(isRunSetup) {
                        activity.startActivity(new Intent(activity, SetupWizard1.class));
                        activity.finish();
                    }
                }
            });
            builder.setNegativeButton("Don't accept", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    refuse(activity);
                }
            });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    refuse(activity);
                }
            });
            // UNCOMMENT TO ENABLE EULA
            //builder.setMessage(readFile(activity, R.raw.eula));
            new LoadEula(activity, builder).execute();
        }
    }
    
    static class LoadEula extends NetworkHandlerTask<Void, String, Void> {
        private AlertDialog.Builder builder;
        private ProgressDialog pd;
        private Context cx;
        
        LoadEula(Context cx, AlertDialog.Builder builder) {
            this.builder = builder;
            this.cx = cx;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(cx);
            pd.setTitle("Loading");
            pd.setMessage("Please wait while we load License Agreement...");
            pd.setIndeterminate(true);
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            final String url = "http:" + Global.BASE_URL + "/eula.txt";
            final HttpGet get = new HttpGet(url);

            HttpEntity entity = null;
            try {
                final HttpResponse response = HttpManager.execute(get);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    entity = response.getEntity();

                    InputStream in = null;
                    OutputStream out = null;

                    try {
//                        in = new GZIPInputStream(entity.getContent());
                        in = entity.getContent();
//                        final ByteArrayOutputStream fos = new ByteArrayOutputStream(IOUtilities.IO_BUFFER_SIZE);
//                        out = new BufferedOutputStream(fos, IOUtilities.IO_BUFFER_SIZE);
                        out = new ByteArrayOutputStream(IOUtilities.IO_BUFFER_SIZE);
                        IOUtilities.copy(in, out);
                        out.flush();
                        
                        publishProgress(out.toString());
                    } catch (IOException e) {
                        android.util.Log.e(Global.LOG_TAG, "Could not load image from " + url, e);
                    } finally {
                        IOUtilities.closeStream(in);
                        IOUtilities.closeStream(out);
                        
                        in  = null;
                        out = null;
                    }
                }
            } catch (IOException e) {
                android.util.Log.e(Global.LOG_TAG, "Could not load image from " + url, e);
            } finally {
                if (entity != null) {
                    try {
                        entity.consumeContent();
                    } catch (IOException e) {
                        android.util.Log.e(Global.LOG_TAG, "Could not load image from " + url, e);
                    }
                }
            }
            
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            pd.dismiss();
            
            builder.setMessage(values[0]);
            builder.create().show();
        }
    }

    private static void accept(SharedPreferences preferences) {
        preferences.edit().putBoolean(PreferencesActivity.PREF_EULA_ACCEPTED, true).commit();
    }

    private static void refuse(Activity activity) {
        activity.finish();
    }
}
